package com.example.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Date 2021/9/12
 * @Created by Jonathan
 */
public class ShellExecutor {
    private static void run() throws Exception {
        //Process process;
        List<String> command = new LinkedList<>();
        //init process builder
        ProcessBuilder processBuilder = new ProcessBuilder();
        // setting up a working directory
        processBuilder.directory(new File("/opt/"));
        // merge error information to standard output stream
        processBuilder.redirectErrorStream(true);

        // setting up user to run commands
        command.add("sudo");
        command.add("-u");
        command.add("root");
        command.add("sh");
        //command.addAll(commandOptions());
        command.add("/opt/test.sh");

        // setting commands
        processBuilder.command(command);
        Process process = processBuilder.start();
        // run 阻塞的
        boolean waitFor = process.waitFor(10, TimeUnit.SECONDS);
        System.out.println("status:" + waitFor);
        //ExecutorService service = Executors.newFixedThreadPool(1);
        List<String> logBuffer = new ArrayList<>();
        BufferedReader inReader = null;
        try {

            inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = inReader.readLine()) != null) {
                logBuffer.add(line);
            }
        } catch (Exception e) {
            System.out.println("error.");
        }
        System.out.println("logBuffer:" + logBuffer);
    }

    public static void main(String[] args) throws Exception {
        System.out.println("start run shell");
        run();
        System.out.println("end run shell");
    }
}
